package com.web.Servlet;

import com.Service.UserService;
import com.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service=new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中文乱码问题
        request.setCharacterEncoding("UTF-8");

        //1.接收用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String remember = request.getParameter("remember");

        User user = service.login(username, password);

        if(user!=null)
        {
            //登陆成功

            if("1".equals(remember))
            {
                username= URLEncoder.encode(username);

                Cookie u_cookie = new Cookie("username",username);
                Cookie p_cookie = new Cookie("password",password);

                u_cookie.setMaxAge(60*60*24*7);
                p_cookie.setMaxAge(60*60*24*7);

                response.addCookie(u_cookie);
                response.addCookie(p_cookie);

            }

            HttpSession session = request.getSession();

            session.setAttribute("user",user);

            //Session转发页面
            String path = request.getContextPath();
            response.sendRedirect(path+"/selectServlet");
        }else {
            request.setAttribute("Login_msg","用户名或密码错误");

            request.getRequestDispatcher("/Login.jsp").forward(request,response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
